package handlers

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Book struct {
	ID          uint   `json:"id" gorm:"primaryKey"`
	Title       string `json:"title"`
	Author      string `json:"author"`
	ISBN        string `json:"isbn"`
	PublishYear int    `json:"publish_year"`
	Available   bool   `json:"available" gorm:"default:true"`
}

func GetBooks(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var books []Book
		db.Find(&books)
		c.JSON(http.StatusOK, books)
	}
}

func CreateBook(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var book Book
		if err := c.ShouldBindJSON(&book); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		db.Create(&book)
		c.JSON(http.StatusCreated, book)
	}
}

func GetBook(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Param("id"))
		var book Book
		if err := db.First(&book, id).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "图书未找到"})
			return
		}
		c.JSON(http.StatusOK, book)
	}
}

func UpdateBook(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Param("id"))
		var book Book
		if err := db.First(&book, id).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "图书未找到"})
			return
		}
		if err := c.ShouldBindJSON(&book); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		db.Save(&book)
		c.JSON(http.StatusOK, book)
	}
}

func DeleteBook(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, _ := strconv.Atoi(c.Param("id"))
		var book Book
		if err := db.First(&book, id).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "图书未找到"})
			return
		}
		db.Unscoped().Delete(&book)
		c.JSON(http.StatusOK, gin.H{"message": "图书已删除"})
	}
}

func SearchBooks(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query := c.Query("q")
		var books []Book
		db.Where("title LIKE ? OR author LIKE ?", "%"+query+"%", "%"+query+"%").Find(&books)
		c.JSON(http.StatusOK, books)
	}
}
